﻿using System;
using System.IO;
using SlimDX;
using Editor.Rendering;
using Editor.Mesh;

namespace Editor
{
    partial class EditorDocument
    {
        private void LoadScene(String sceneFileName)
        {
            Entity entity1 = CreateEntity("BottomSphere", 1.0f, @"c:\temp\data\PositionNormalUV.fx", @"c:\temp\data\jupiter.jpg", @"c:\temp\data\jupiter.smd");
            Entity entity2 = CreateEntity("TopSphere", 10.0f, @"c:\temp\data\PositionNormalUV.fx", @"c:\temp\data\jupiter.jpg", @"c:\temp\data\jupiter.smd");
            entity2.Parent = entity1;
            entity1.LocalTransform = Matrix.Translation(0, 0, 64);
            entity2.LocalTransform = Matrix.Translation(0, 0, 128);
        }

		private bool SaveScene(String sceneFileName)
        {
			if (!CanSaveFile(sceneFileName))
				return false;

			//
			return true;
		}

		private bool CanSaveFile(String fileName)
		{
			bool bSave = true;
			if (File.Exists(fileName))
			{
				if ((File.GetAttributes(fileName) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
				{
					// TODO: Open for Edit in Perforce?
					bSave = false;
				}
			}
			else
			{
				// TODO: Add to Perforce
			}

			return bSave;
		}

        public Entity CreateEntity(String entityName, float mass, String shaderFileName, String textureFileName, String meshFileName)
        {
            Shader shader = FindShader(shaderFileName);
            if (shader == null)
            {
                shader = new Rendering.Shader(RenderUtils.Direct3DDevice, shaderFileName);
                m_Shaders.Add(shader);
            }

            Material material = FindMaterial(shader, textureFileName);
            if (material == null)
            {
                material = new Material(RenderUtils.Direct3DDevice, shader, textureFileName);
                m_Materials.Add(material);
            }

            MeshData mesh = FindMesh(meshFileName);
            if (mesh == null)
            {
                mesh = SmdLoader.FromFile(meshFileName);
                mesh.CreateRenderingBuffers(RenderUtils.Direct3DDevice);
                m_Meshes.Add(mesh);
            }

            StillDesign.PhysX.ActorDescription sphereDesc = new StillDesign.PhysX.ActorDescription()
            {
                Name = entityName,
                Shapes = { new StillDesign.PhysX.SphereShapeDescription(64.0f) },
                BodyDescription = new StillDesign.PhysX.BodyDescription(mass),
                GlobalPose = Matrix.Identity
            };

            Entity entity = new Entity();
            entity.AddMeshInstance(material, mesh);
            entity.Actor = PhysicsUtils.PhysXScene.CreateActor(sphereDesc);
            entity.LocalTransform = Matrix.Identity;
            m_Entities.Add(entity);

            return entity;
        }
    }
}
